import os
import streamlit as st
from large_model.agent_executors import Executors
from streamlit_model.streamlit_utils.file_uploader import read_uploaded_file
from streamlit_model.streamlit_utils.session_utils import load_session, save_session
from utils.file_dir import get_doc_md_dir

PAGE_KEY = "uploaded_file_api_case"


def uploaded_file_api_case():
    st.write("根据接口文档按照要求生成用例")

    cached = load_session(PAGE_KEY)

    if st.session_state.pop("clear_triggered", False):
        st.session_state.clear()
        st.rerun()

    if "task_executed" not in st.session_state:
        st.session_state.update(cached)

    if st.session_state.get("task_executed"):
        _, center_output, _ = st.columns([1, 3, 1])
        with center_output:
            st.success("测试用例生成完成！")
            st.markdown(st.session_state["output"])

    cached_file_name = cached.get("uploaded_file_name")
    cached_review = cached.get("review_method", "需求文档是单个模块完整的功能")
    cached_desc = cached.get("description", "请你对:接口名称 接口进行【单接口】的测试用例的编写并保存")
    cached_content = cached.get("uploaded_file_content", "")
    cached_file_path = cached.get("file_path")

    _, upload_col, _ = st.columns([1, 3, 1])
    with upload_col:
        uploaded_file = st.file_uploader("选择接口文档进行上传，只能上传一个文件",
                                         type=["doc", "docx", "pdf"])

    # 读取文件内容
    # 读取文件内容
    file_content = ""
    file_name = None
    file_path = None

    if uploaded_file is not None:
        # 1. 先读字节
        file_bytes = uploaded_file.read()

        # 2. 立即把文件保存到 get_doc_md_dir 返回的路径
        file_name = uploaded_file.name
        file_path = get_doc_md_dir(file_name)  # 新增
        with open(file_path, "wb") as f:  # 新增
            f.write(file_bytes)  # 新增

        # 3. 再解析内容
        file_content = read_uploaded_file(file_bytes, file_name)

    elif cached_file_name and cached_content:
        file_content = cached_content
        file_name = cached_file_name
        file_path = cached_file_path

    _, sel_col, _ = st.columns([1, 3, 1])
    with sel_col:
        opts = ["单接口测试用例", "接口关联测试用例"]
        review_method = st.selectbox("请选择文档处理方式---只有一种", opts, index=0)

        # 以下判断可以保留，但已在上面的 if 分支里赋值，实际不会走到 else
        if uploaded_file is not None:
            file_path = file_name
        else:
            file_path = cached_file_path

        description = ""
        if review_method == "单接口测试用例":
            description = st.text_area("输入接口用例生成的描述", value="请你对:接口名称 接口进行【单接口】的测试用例的编写并保存:\n", height=120)
        else:
            description = st.text_area("输入接口用例生成的描述", value="请你对:接口名称 接口进行【多接口】的测试用例的编写，接口关联主要是编写正向的测试用例，编写完之后进行保存", height=120)

    # 即时保存
    need_save = (
            file_name != cached_file_name or
            review_method != cached_review or
            description != cached_desc or
            file_content != cached_content or
            file_path != cached_file_path
    )
    if need_save and not st.session_state.get("clear_triggered", False):
        save_session(PAGE_KEY, {
            "uploaded_file_name": file_name,
            "uploaded_file_content": file_content,
            "review_method": review_method,
            "description": description,
            "file_path": file_path,
            "task_executed": st.session_state.get("task_executed", False),
            "output": st.session_state.get("output", "")
        })

    _, btn_col, _ = st.columns([2, 1, 2])
    with btn_col:
        generate_button = st.button("生成用例", use_container_width=True)
        if st.button("清除缓存", use_container_width=True):
            save_session(PAGE_KEY, {})
            st.session_state["clear_triggered"] = True
            st.rerun()

        if generate_button and file_content:
            executors = Executors()
            with st.spinner("正在生成测试用例..."):
                    output = executors.interfaces_documents_mian(file_path, description)

            data = {
                "uploaded_file_name": file_name,
                "uploaded_file_content": file_content,
                "review_method": review_method,
                "description": description,
                "file_path": file_path,
                "task_executed": True,
                "output": output
            }
            st.session_state.update(data)
            if not st.session_state.get("clear_triggered", False):
                save_session(PAGE_KEY, data)
            st.rerun()
